package dao;

import pojo.Message;
import utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class MessageDao {
    /**
     * 查看所有留言
     */
    public List<Message> selectAll(){
        List<Message> messageList = new ArrayList<>();
        //1. 获取链接
        //2. 拼接SQL
        //3. 执行SQL
        //4. 拼接执行结果
        Connection connection = DBUtils.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try{
           String sql = "select * from messages";
           statement = connection.prepareStatement(sql);
           resultSet = statement.executeQuery();
           while (resultSet.next()){
               Message message = new Message();
               message.setFrom(resultSet.getString("from"));
               message.setTo(resultSet.getString("to"));
               message.setMessage(resultSet.getString("message"));
               messageList.add(message);
           }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtils.close(connection,statement,resultSet);
        }
        return messageList;
    }
    /**
     * 插入新留言
     */
    public void insert(Message message) {
        Connection connection = DBUtils.getConnection();
        PreparedStatement statement = null;
        try {
            String sql = "insert into messages values(?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,message.getFrom());
            statement.setString(2,message.getTo());
            statement.setString(3,message.getMessage());

            statement.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtils.close(connection,statement,null);
        }
    }
}
